// See https://aka.ms/new-console-template for more information
using System.Reflection;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;

public class TypeInferenceRewriter : CSharpSyntaxRewriter
{
    private readonly SemanticModel _semanticModel;

    public TypeInferenceRewriter(SemanticModel semanticModel) => _semanticModel = semanticModel;

    // 重写本地变量声明语句的语法节点
    public override SyntaxNode? VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node)
    {
        if (node.Declaration.Variables.Count > 1)
        {
            return node;
        }

        if (node.Declaration.Variables[0].Initializer == null)
        {
            return node;
        }

        var declarator = node.Declaration.Variables.First();
        var variableTypeName = node.Declaration.Type;

        var variableType = (ITypeSymbol)_semanticModel.GetSymbolInfo(variableTypeName).Symbol;

        var initializerInfo = _semanticModel.GetTypeInfo(declarator.Initializer.Value);
        if (SymbolEqualityComparer.Default.Equals(variableType, initializerInfo.Type))
        {
            TypeSyntax varTypeName = SyntaxFactory.IdentifierName("var")
                .WithLeadingTrivia(variableTypeName.GetLeadingTrivia())
                .WithTrailingTrivia(variableTypeName.GetTrailingTrivia());

            return node.ReplaceNode(variableTypeName, varTypeName);
        }
        else
        {
            return node;
        }

    }
}
